import React, { useState } from 'react';
import { Table, Avatar, Tag, Button, Space, Tooltip, Modal, Input, InputNumber } from 'antd';
import {
  CrownOutlined,
  UserOutlined,
  DeleteOutlined
} from '@ant-design/icons';

const MemberTable = ({
  members,
  userRole,
  isLoading,
  operationLoading,
  onUpdateMemberRole,
  onRemoveMember
}) => {
  const [banDuration, setBanDuration] = useState(0);
  const [removeModalVisible, setRemoveModalVisible] = useState(false);
  const [removingMember, setRemovingMember] = useState(null);

  // 格式化日期
  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 处理移除成员
  const handleRemoveMember = (userId, username) => {
    // 重置禁止时间
    setBanDuration(0);
    
    // 设置要移除的成员信息
    setRemovingMember({ userId, username });
    
    // 显示自定义模态框
    setRemoveModalVisible(true);
  };

  // 确认移除成员
  const confirmRemoveMember = () => {
    if (!removingMember) return;
    
    onRemoveMember(removingMember.userId, removingMember.username, banDuration);
    
    // 关闭模态框并重置状态
    setRemoveModalVisible(false);
    setRemovingMember(null);
    setBanDuration(0);
  };

  // 取消移除成员
  const cancelRemoveMember = () => {
    setRemoveModalVisible(false);
    setRemovingMember(null);
    setBanDuration(0);
  };

  // 成员表格列定义
  const columns = [
    {
      title: '成员',
      key: 'member',
      render: (_, record) => (
        <div className="member-avatar-cell">
          <Avatar 
            src={record.avatarUrl} 
            size={40}
            className="member-avatar"
          >
            {record.username.charAt(0).toUpperCase()}
          </Avatar>
          <div className="member-info">
            <div className="member-name">{record.username}</div>
            <div className="member-id">ID: {record.userId}</div>
          </div>
        </div>
      )
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => (
        role === 'admin' ? 
          <Tag color="blue" icon={<CrownOutlined />}>管理员</Tag> : 
          <Tag color="green" icon={<UserOutlined />}>成员</Tag>
      )
    },
    {
      title: '加入时间',
      dataIndex: 'joinedAt',
      key: 'joinedAt',
      render: (date) => formatDate(date)
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => {
        const currentUser = JSON.parse(localStorage.getItem('user') || '{}');
        const isCurrentUser = record.userId === currentUser.userId;
        

        
        // 如果当前用户不是管理员，不显示任何操作
        if (userRole !== 'admin') {
          return <span style={{ color: '#999' }}>-</span>;
        }

        // 计算管理员数量
        const adminCount = members.filter(member => member.role === 'admin').length;
        
        // 如果是当前用户自己
        if (isCurrentUser) {
          return (
            <Space className="member-actions">
              {record.role === 'admin' ? (
                // 如果是管理员且只有一个管理员，不能降级自己
                adminCount <= 1 ? (
                  <Tooltip title="网络中必须至少保留一名管理员">
                    <Button
                      type="link"
                      icon={<UserOutlined />}
                      disabled
                      size="small"
                    >
                      降级
                    </Button>
                  </Tooltip>
                ) : (
                  <Tooltip title="降为普通成员">
                    <Button
                      type="link"
                      icon={<UserOutlined />}
                      onClick={() => onUpdateMemberRole(record.userId, 'member', record.username)}
                      loading={operationLoading}
                      size="small"
                    >
                      降级
                    </Button>
                  </Tooltip>
                )
              ) : (
                <span style={{ color: '#999' }}>-</span>
              )}
              {/* 管理员不能移除自己 */}
              {record.role === 'admin' ? (
                <Tooltip title="管理员不能移除自己">
                  <Button
                    type="link"
                    danger
                    icon={<DeleteOutlined />}
                    disabled
                    size="small"
                  >
                    移除
                  </Button>
                </Tooltip>
              ) : (
                <Tooltip title="移除成员">
                  <Button
                    type="link"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => handleRemoveMember(record.userId, record.username)}
                    loading={operationLoading}
                    size="small"
                  >
                    移除
                  </Button>
                </Tooltip>
              )}
            </Space>
          );
        }

        // 如果是其他用户
        return (
          <Space className="member-actions">
            {record.role === 'member' ? (
              // 可以提升普通成员为管理员
              <Tooltip title="提升为管理员">
                <Button
                  type="link"
                  icon={<CrownOutlined />}
                  onClick={() => onUpdateMemberRole(record.userId, 'admin', record.username)}
                  loading={operationLoading}
                  size="small"
                >
                  提升
                </Button>
              </Tooltip>
            ) : (
              // 不能降级其他管理员
              <Tooltip title="不能降级其他管理员">
                <Button
                  type="link"
                  icon={<UserOutlined />}
                  disabled
                  size="small"
                >
                  降级
                </Button>
              </Tooltip>
            )}
            {/* 根据API文档：不能移除管理员成员 */}
            {record.role === 'admin' ? (
              <Tooltip title="不能移除管理员成员">
                <Button
                  type="link"
                  danger
                  icon={<DeleteOutlined />}
                  disabled
                  size="small"
                >
                  移除
                </Button>
              </Tooltip>
            ) : (
              <Tooltip title="移除成员">
                <Button
                  type="link"
                  danger
                  icon={<DeleteOutlined />}
                  onClick={() => handleRemoveMember(record.userId, record.username)}
                  loading={operationLoading}
                  size="small"
                >
                  移除
                </Button>
              </Tooltip>
            )}
          </Space>
        );
      }
    }
  ];

  return (
    <>
      <Table
        columns={columns}
        dataSource={members}
        rowKey="userId"
        loading={isLoading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => 
            `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
        }}
        locale={{
          emptyText: '暂无成员信息'
        }}
      />
      
      {/* 移除成员确认对话框 */}
      <Modal
        title={`移除成员 ${removingMember?.username || ''}`}
        open={removeModalVisible}
        onOk={confirmRemoveMember}
        onCancel={cancelRemoveMember}
        okText="确认移除"
        cancelText="取消"
        okType="danger"
        width={500}
        confirmLoading={operationLoading}
      >
        <div style={{ padding: '16px 0' }}>
          <p style={{ marginBottom: '16px' }}>
            确定要移除成员 <strong>{removingMember?.username}</strong> 吗？
          </p>
          <div style={{ marginBottom: '16px' }}>
            <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
              禁止重新加入时长（小时）：
            </label>
            <InputNumber
              placeholder="输入0表示不禁止"
              value={banDuration}
              min={0}
              max={4320}
              style={{ width: '100%' }}
              onChange={(value) => setBanDuration(value || 0)}
            />
            <div style={{ marginTop: '8px', color: '#666', fontSize: '12px' }}>
              • 输入 0 表示不禁止重新加入<br/>
              • 最大可设置 4320 小时（180天）<br/>
              • 系统会自动发送邮件通知被移除的成员
            </div>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default MemberTable;